package com.ctn.information.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;

import com.ctn.information.R;
import com.ctn.information.content.NewsFragment;
import com.ctn.information.util.AppUtil;
import com.ctn.information.view.model.TabPager;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

/**
 * Tab View and Pager View界面(基本类Fragment)
 * 
 * @author HLJ
 *
 */
public class TabPagerView extends Fragment {

	TabHost mTabHost;
    ViewPager  mViewPager;
    TabsAdapter mTabsAdapter;
    HorizontalScrollView hsv;
    protected static int first = 0;
    protected static int last = 1;
    private static float lastValue = 0F;
    private static float drag_diff = 50F;
    static int selected=0;
    private SlidingMenu sm=null;
    
    public void bindSlidingMenu(SlidingMenu sm){
    	AppUtil.SLIDING_MENU = sm;
    	this.sm = sm; 
    }
    
	public TabPagerView(){
		
	}
	
	/**
	 * 子类只需重写这个方法，设置数据
	 * 
	 * @return
	 */
	protected List<TabPager> setTabPagerList(){
		List<TabPager> list = new ArrayList<TabPager>();
		TabPager tp = new TabPager();
		tp.clazz = NewsFragment.class;
		tp.tag = "Example";
		tp.title = "Example";
		tp.model = TabPager.TAB_PAGER_DEFAULT_MODEL;
		list.add(tp);
		return list;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.fragment_tabs_pager, null);
		
        mTabHost = (TabHost)v.findViewById(android.R.id.tabhost);
        hsv = (HorizontalScrollView)v.findViewById(R.id.hsv_tab);
        AppUtil.TAB_HEIGHT = hsv.getHeight();
        mTabHost.setup();
        mViewPager = (ViewPager)v.findViewById(R.id.pager);
        
        LinearLayout mlinearLayout = null;

        TextView tv = null;
        sm = (sm == null)?sm = AppUtil.SLIDING_MENU:sm;
		
        mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager,sm,hsv);

        List<TabPager> list = setTabPagerList();
        last = list.size() - 1;
        for (TabPager tp : list) {
        	if (tp.model == TabPager.TAB_PAGER_CUSTOMER_MODEL) {
        		mlinearLayout = (LinearLayout)inflater.inflate(R.layout.custmor_tab_widget, null);
        		tv = (TextView)mlinearLayout.findViewById(R.id.tab_row_title);
			}else{
				if (tp.layoutId == 0) {
					mlinearLayout = (LinearLayout)inflater.inflate(R.layout.custmor_tab_widget, null);
					tv = (TextView)mlinearLayout.findViewById(R.id.tab_row_title);
				}else{
					mlinearLayout = (LinearLayout)inflater.inflate(tp.layoutId, null);
					tv = (TextView)mlinearLayout.findViewById(tp.viewId);
				}
			}
			tv.setText(tp.title);
			mTabsAdapter.addTab(mTabHost.newTabSpec(tp.tag).setIndicator(mlinearLayout),
	                tp.clazz, tp.bundle);
		}
        
        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }
        
		return v;
	}
	
	/**
	 * Tab适配器
	 * 
	 * @author HLJ
	 */
	public static class TabsAdapter extends FragmentPagerAdapter
		    implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
		private final Context mContext;
		private final TabHost mTabHost;
		private final ViewPager mViewPager;
		private final SlidingMenu sm;
		private final HorizontalScrollView hsv;
		private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
		private final int halfScreen =AppUtil.WIDTH_PX/2; 
		private final Fragment fragment;
		
		
		static final class TabInfo {
		    private final String tag;
		    private final Class<?> clss;
		    private final Bundle args;
		
		    TabInfo(String _tag, Class<?> _class, Bundle _args) {
		        tag = _tag;
		        clss = _class;
		        args = _args;
		    }
		}
		
		/**
		 * Tab创建工厂
		 * 
		 * @author HLJ
		 *
		 */
		static class TabFactory implements TabHost.TabContentFactory {
		    private final Context mContext;
		    public TabFactory(Context context) {
		        mContext = context;
		    }
		
		    @Override
		    public View createTabContent(String tag) {
		        View v = new View(mContext);
		        v.setMinimumWidth(0);
		        v.setMinimumHeight(0);
		        return v;
		    }
		}
		
		
		public TabsAdapter(Fragment activity, TabHost tabHost, ViewPager pager,
				SlidingMenu slidmenu,HorizontalScrollView hsv) {
		    super(activity.getChildFragmentManager());
		    mContext = activity.getActivity();
		    this.fragment = activity;
		    mTabHost = tabHost;
		    mViewPager = pager;
		    this.hsv = hsv;
		    sm = slidmenu;
		    mTabHost.setOnTabChangedListener(this);
		    mViewPager.setAdapter(this);
		    mViewPager.setOnPageChangeListener(this);
		    mViewPager.setOnTouchListener(new View.OnTouchListener() {
				
				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {
					
					switch (arg1.getAction()) {
					case MotionEvent.ACTION_DOWN:
						lastValue = arg1.getX();
						break;
					case MotionEvent.ACTION_MOVE:
						if (lastValue == -1F) {
							lastValue = arg1.getX();
						}
						Log.d("sssss", "LastValue:"+lastValue+" Now:"+arg1.getX() + " Diff:"+(arg1.getX() - lastValue));
						if (selected == first && (arg1.getX() - lastValue) > drag_diff) {
							sm.showMenu();
						}else if(selected == last && (lastValue - arg1.getX()) > drag_diff){
							sm.showSecondaryMenu();
						}
						break;
					case MotionEvent.ACTION_UP:
							lastValue = -1F;
						break;
					default:
						break;
					}
					
					return false;
				}
			});
		}
		
		public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
		    tabSpec.setContent(new TabFactory(mContext));
		    String tag = tabSpec.getTag();
		
		    TabInfo info = new TabInfo(tag, clss, args);
		    mTabs.add(info);
		    mTabHost.addTab(tabSpec);
		    notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
		    return mTabs.size();
		}
		
		@Override
		public Fragment getItem(int position) {
		    TabInfo info = mTabs.get(position);
		    Fragment f = Fragment.instantiate(mContext, info.clss.getName(), info.args);
		    Bundle b = new Bundle();
		    b.putCharSequence("fragmentTag", info.tag);
		    return Fragment.instantiate(mContext, info.clss.getName(), info.args);
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
		    TabInfo info = mTabs.get(position);
//          String id=info.tag;
            SharedPreferences prefer=mContext.getSharedPreferences("CurrentSecondMenuItem", Context.MODE_PRIVATE);
            Editor editor=prefer.edit();
            editor.putString("SecondMenuId",info.tag);
            editor.commit();
		    return super.instantiateItem(container, position);
		};
		
		
		@Override
		public void onTabChanged(String tabId) {
			//===2013-5-27===edit ==start
		    int position = mTabHost.getCurrentTab();
		    
		    mViewPager.setCurrentItem(position,false);
		  //===2013-5-27===edit ==end
		}
		
		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//			Log.d("Test-A", "before-"+lastValue+" now-"+positionOffsetPixels);
			/*if (sm != null) {
				if(position == first && lastValue == positionOffsetPixels){
					Log.d("Test-O-Left", "before-"+lastValue+" now-"+positionOffsetPixels);
					sm.toggle();
					lastValue = -1;
				}else if(position == last && lastValue == positionOffsetPixels){
					Log.d("Test-O-Right", "before-"+lastValue+" now-"+positionOffsetPixels);
					sm.showSecondaryMenu();
					lastValue = -1;
				}else {*/
//					lastValue = positionOffsetPixels;
				/*}
			}*/
//			Log.d("Test-B", "before-"+lastValue+" now-"+positionOffsetPixels);
//				lastValue = positionOffsetPixels;
		}
		
		@Override
		public void onPageSelected(int position) {
		    // Unfortunately when TabHost changes the current tab, it kindly
		    // also takes care of putting focus on it when not in touch mode.
		    // The jerk.
		    // This hack tries to prevent this from pulling focus out of our
		    // ViewPager.
			selected = position;
		    TabWidget widget = mTabHost.getTabWidget();
		    int oldFocusability = widget.getDescendantFocusability();
		    widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
		    mTabHost.setCurrentTab(position);
		    widget.setDescendantFocusability(oldFocusability);
		    View v = mTabHost.getCurrentTabView();
		    int w = v.getWidth();
		    int d = v.getLeft();
		    if (d >= halfScreen) {
				hsv.scrollBy(w, 0);
			}else{
				hsv.scrollBy(-w, 0);
			}
		}
		
		@Override
		public int getItemPosition(Object object) {
		   return FragmentPagerAdapter.POSITION_NONE;
		}
		
		
		@Override
		public void onPageScrollStateChanged(int state) {
		}
	}
}
